package com.dbgs.executer.callback;

import java.util.concurrent.Executor;

public class NormalCallback implements ThreadCallback, AsyncCallback  {

    private ThreadCallback callback;
    private AsyncCallback async;
    private Executor deliver;

    public NormalCallback(ThreadCallback callback, Executor deliver, AsyncCallback async) {
        this.callback = callback;
        this.async = async;
        this.deliver = deliver;
    }

    @Override
    public void onSuccess(final Object o) {
        if (async == null) {
            return;
        }
        deliver.execute(new Runnable() {
            @Override
            public void run() {

                try {
                    async.onSuccess(o);

                }catch (Throwable throwable1){
                    onFailed(throwable1);
                }
            }
        });
    }

    @Override
    public void onFailed(final Throwable throwable) {
        if (async == null) {
            return;
        }
        deliver.execute(new Runnable() {
            @Override
            public void run() {
                async.onFailed(throwable);
            }



        });
    }

    @Override
    public void onError(final String threadName,final Throwable t) {
        onFailed(t);

        if (callback == null) {
            return;
        }
        deliver.execute(new Runnable() {
            @Override
            public void run() {
                callback.onError(threadName,t);
            }
        });
    }

    @Override
    public void onCompleted(final String threadName) {
        if (callback == null) {
            return;
        }
        deliver.execute(new Runnable() {
            @Override
            public void run() {
                callback.onCompleted(threadName);
            }
        });

    }

    @Override
    public void onStart(final String threadName) {
        if (callback == null || async ==null) {
            return;
        }
        deliver.execute(new Runnable() {
            @Override
            public void run() {
                callback.onStart(threadName);
            }
        });
    }
}
